use crate::db::{dao, po};
use crate::dto;
use crate::service::error::Error;
use std::sync::Arc;
use wanmesh_common::error::ResponseError;
use wanmesh_common::net::wireguard;

#[async_trait::async_trait]
pub trait EndpointWireguardConfigService: Send + Sync {
    async fn add(
        &self,
        endpoint_id: &str,
        params: &dto::core::endpoint_wireguard_config::AddParams,
    ) -> Result<(), Error>;

    async fn get(
        &self,
        endpoint_id: &str,
    ) -> Result<dto::core::endpoint_wireguard_config::EndpointWireguardConfig, Error>;

    async fn try_get(
        &self,
        endpoint_id: &str,
    ) -> Result<Option<dto::core::endpoint_wireguard_config::EndpointWireguardConfig>, Error>;

    async fn update(
        &self,
        endpoint_id: &str,
        params: &dto::core::endpoint_wireguard_config::UpdateParams,
    ) -> Result<(), Error>;

    async fn delete(&self, endpoint_id: &str) -> Result<(), Error>;

    async fn exists(
        &self,
        filter: &dto::core::endpoint_wireguard_config::Filter,
    ) -> Result<bool, Error>;
}

pub struct DefaultEndpointWireguardConfigService {
    endpoint_wireguard_config_dao:
        Arc<dyn dao::endpoint_wireguard_config::EndpointWireguardConfigDao>,
}

impl DefaultEndpointWireguardConfigService {
    pub fn new(
        endpoint_wireguard_config_dao: Arc<
            dyn dao::endpoint_wireguard_config::EndpointWireguardConfigDao,
        >,
    ) -> Self {
        Self {
            endpoint_wireguard_config_dao,
        }
    }
}

#[async_trait::async_trait]
impl EndpointWireguardConfigService for DefaultEndpointWireguardConfigService {
    async fn add(
        &self,
        endpoint_id: &str,
        params: &dto::core::endpoint_wireguard_config::AddParams,
    ) -> Result<(), Error> {
        if self
            .endpoint_wireguard_config_dao
            .exists(dao::endpoint_wireguard_config::Filter {
                endpoint_id: Some(endpoint_id.to_string()),
                ..Default::default()
            })
            .await?
        {
            return Err(Error::ResponseError(
                ResponseError::endpoint_wireguard_config_already_exist(endpoint_id),
            ));
        }

        let private_key = wanmesh_common::net::wireguard::key::PrivateKey::random();
        let wireguard_interface_private_key =
            po::ActiveValue::Set(po::Base64Bytes::from(private_key.as_slice()));

        let mut wireguard_interface_listen_port = po::ActiveValue::NotSet;
        if let Some(config) = &params.config
            && let Some(interface) = &config.interface
        {
            wireguard_interface_listen_port = po::option_to_active_value(interface.listen_port)
        }

        self.endpoint_wireguard_config_dao
            .insert(po::endpoint_wireguard_config::ActiveModel {
                id: Default::default(),
                endpoint_id: po::ActiveValue::Set(endpoint_id.to_string()),
                wireguard_interface_private_key,
                wireguard_interface_listen_port,
                create_timestamp_millis: Default::default(),
                update_timestamp_millis: Default::default(),
            })
            .await?;
        Ok(())
    }

    async fn get(
        &self,
        endpoint_id: &str,
    ) -> Result<dto::core::endpoint_wireguard_config::EndpointWireguardConfig, Error> {
        let config = self.try_get(endpoint_id).await?.ok_or(
            ResponseError::endpoint_wireguard_config_not_found(endpoint_id),
        )?;

        Ok(config)
    }

    async fn try_get(
        &self,
        endpoint_id: &str,
    ) -> Result<Option<dto::core::endpoint_wireguard_config::EndpointWireguardConfig>, Error> {
        let filter = dao::endpoint_wireguard_config::Filter {
            endpoint_id: Some(endpoint_id.to_string()),
            ..Default::default()
        };

        if let Some(m) = self.endpoint_wireguard_config_dao.try_get(filter).await? {
            return Ok(Some(m.try_into()?));
        }

        Ok(None)
    }

    async fn update(
        &self,
        endpoint_id: &str,
        params: &dto::core::endpoint_wireguard_config::UpdateParams,
    ) -> Result<(), Error> {
        if params == &Default::default() {
            return Ok(());
        }

        let filter = dao::endpoint_wireguard_config::Filter {
            endpoint_id: Some(endpoint_id.to_string()),
            ..Default::default()
        };

        if !self
            .endpoint_wireguard_config_dao
            .exists(filter.clone())
            .await?
        {
            return Err(Error::ResponseError(
                ResponseError::endpoint_wireguard_config_not_found(endpoint_id),
            ));
        }

        self.endpoint_wireguard_config_dao
            .update(filter, params.into())
            .await?;

        Ok(())
    }

    async fn delete(&self, endpoint_id: &str) -> Result<(), Error> {
        let filter = dao::endpoint_wireguard_config::Filter {
            endpoint_id: Some(endpoint_id.to_string()),
            ..Default::default()
        };

        self.endpoint_wireguard_config_dao.delete(filter).await?;

        Ok(())
    }

    async fn exists(
        &self,
        filter: &dto::core::endpoint_wireguard_config::Filter,
    ) -> Result<bool, Error> {
        let exists = self
            .endpoint_wireguard_config_dao
            .exists(filter.into())
            .await?;

        Ok(exists)
    }
}

impl TryFrom<&po::endpoint_wireguard_config::Model>
    for dto::core::endpoint_wireguard_config::EndpointWireguardConfig
{
    type Error = anyhow::Error;
    fn try_from(value: &po::endpoint_wireguard_config::Model) -> Result<Self, Self::Error> {
        let key =
            wireguard::key::PublicKey::try_from(value.wireguard_interface_private_key.as_slice())?;
        Ok(
            dto::core::endpoint_wireguard_config::EndpointWireguardConfig {
                config: dto::core::endpoint_wireguard_config::WireguardConfig {
                    interface: dto::core::endpoint_wireguard_config::WireguardInterfaceConfig {
                        private_key: key.to_bytes(),
                        listen_port: value.wireguard_interface_listen_port,
                    },
                },
            },
        )
    }
}

impl TryFrom<po::endpoint_wireguard_config::Model>
    for dto::core::endpoint_wireguard_config::EndpointWireguardConfig
{
    type Error = anyhow::Error;
    fn try_from(value: po::endpoint_wireguard_config::Model) -> Result<Self, Self::Error> {
        Self::try_from(&value)
    }
}

impl From<&dto::core::endpoint_wireguard_config::Filter>
    for dao::endpoint_wireguard_config::Filter
{
    fn from(value: &dto::core::endpoint_wireguard_config::Filter) -> Self {
        Self {
            endpoint_id: value.endpoint_id.clone(),
        }
    }
}

impl From<dto::core::endpoint_wireguard_config::Filter> for dao::endpoint_wireguard_config::Filter {
    fn from(value: dto::core::endpoint_wireguard_config::Filter) -> Self {
        Self::from(&value)
    }
}

impl From<&dto::core::endpoint_wireguard_config::UpdateParams>
    for dao::endpoint_wireguard_config::UpdateParams
{
    fn from(value: &dto::core::endpoint_wireguard_config::UpdateParams) -> Self {
        if value == &Default::default() {
            return Self::default();
        }

        let mut wireguard_interface_listen_port = po::ActiveValue::NotSet;

        if let Some(config) = &value.config
            && let Some(interface) = &config.interface
        {
            wireguard_interface_listen_port =
                po::nullable_option_to_active_value(interface.listen_port);
        }

        Self {
            wireguard_interface_private_key: Default::default(),
            wireguard_interface_listen_port,
        }
    }
}

impl From<dto::core::endpoint_wireguard_config::UpdateParams>
    for dao::endpoint_wireguard_config::UpdateParams
{
    fn from(value: dto::core::endpoint_wireguard_config::UpdateParams) -> Self {
        Self::from(&value)
    }
}
